package com.yin.context.support;

import com.yin.beans.BeanDefinition;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class BeanDefinitionReader {

    private Properties config = new Properties();
    private List<String> registyBeanClasses = new ArrayList<>();
    private final String SCAN_PACKAGE = "scanPackage";

    public BeanDefinitionReader(){

    }

    public BeanDefinitionReader(String... location){

        InputStream fis = this.getClass().getClassLoader()
                .getResourceAsStream(location[0].replace("classpath:",""));
        try {
            config.load(fis);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != fis){
                try {
                    fis.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        doScanner(config.getProperty(SCAN_PACKAGE));
    }


    public BeanDefinition registerBean(String className){

        BeanDefinition beanDefinition = new BeanDefinition();
        beanDefinition.setBeanClassName(className);
        beanDefinition.setFactoryBeanName(toLowerFirstCase(className.substring(className.lastIndexOf(".")+1)));
        return beanDefinition;
    }

    public String toLowerFirstCase(String words){
        if(words == null || words.isEmpty()) return null;
        char[] ws = words.toCharArray();
        ws[0] += 32;
        return String.valueOf(ws);
    }

    public Properties getConfig(){
        return this.config;
    }

    public List<String> loadBeanDefinitions(){
        return this.registyBeanClasses;
    }
    private void doScanner(String scanPackage){
        URL url = this.getClass().getClassLoader()
                .getResource("/" + scanPackage.replaceAll("\\.","/"));
        File classpath = new File(url.getFile());
        for (File file : classpath.listFiles()){
            if(file.isDirectory()){
                doScanner(scanPackage + "." + file.getName());
            }else {
                if(!file.getName().endsWith(".class")) continue;
                String className = scanPackage + "." + file.getName().replace(".class","");
                registyBeanClasses.add(className);
            }
        }
    }


}
